<template>
  <div>
    <el-form ref="form" :model="form" label-width="160px">
      <el-form-item label="主题">
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      <el-form-item label="菜单" prop="menuId">
        <el-cascader
          v-model="form.menuId"
          :options="menuTreeOptions"
          :props="cascaderProps"
          placeholder="请选择菜单"
          clearable
          style="width: 100%"
          filterable
          @change="handleMenuChange"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="排序">
        <el-input-number v-model="form.sort" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item label="WAP端封面">
        <FileUpload
          :limit="1"
          v-model="form.wapImgUrl"
          :fileType="['jpg', 'jpeg', 'png']"
        />
      </el-form-item>
      <el-form-item label="PC端封面">
        <FileUpload
          :limit="1"
          v-model="form.pcImgUrl"
          :fileType="['jpg', 'jpeg', 'png']"
        />
      </el-form-item>
      <el-form-item label="视频上传">
        <FileUpload
          :limit="1"
          v-model="form.fileUrl"
          :src="baseUrl + form.fileUrl"
          :fileType="['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm']"
        />
      </el-form-item>
      <el-form-item label="内容介绍">
        <Tinymce v-model="form.contentIntroduce" :height="400" />
      </el-form-item>
    </el-form>

    <div style="margin: 20px 0; display: flex; justify-content: center">
      <el-button type="primary" @click="onSubmit">保存</el-button>
      <el-button @click="onCancel">取消</el-button>
    </div>
  </div>
</template>
<script>
import {
  create,
  edit,
  detail,
} from "@/api/activityConfiguration";
import { getMenuTree } from "@/api/activityMenu";
import Tinymce from "@/components/Tinymce/Tinymce.vue";
export default {
  components: {
    Tinymce
  },
  props: ["activityType"],
  data() {
    return {
      form: {
        id: null,
        menuId: null,
        title: "",
        sort: 0,
        wapImgUrl: "",
        pcImgUrl: "",
        contentIntroduce: "",
        fileUrl: "",
      },
      menuTreeOptions: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      cascaderProps: {
        value: 'id',
        label: 'menuName',
        children: 'children',
        emitPath: true, // 返回路径数组，用于正确显示
        checkStrictly: true // 可以选择任意层级
      },
    };
  },
  mounted() {
    this.getMenuTreeData();
  },
  methods: {
    // 获取菜单树数据
    getMenuTreeData() {
      getMenuTree().then((res) => {
        if (res.code === 200 && res.data) {
          // 将菜单树数据转换为 el-cascader 需要的格式
          this.menuTreeOptions = this.convertMenuTreeToCascader(res.data);
        }
      }).catch((error) => {
        console.error("获取菜单树失败:", error);
        this.$message.error("获取菜单树失败，请重试");
      });
    },
    // 将菜单树转换为级联选择器格式
    convertMenuTreeToCascader(treeData) {
      if (!Array.isArray(treeData)) {
        return [];
      }
      return treeData.map(item => {
        // 支持 child 或 children 字段
        const children = item.children || item.child;
        const node = {
          id: String(item.id), // 统一转换为字符串类型
          menuName: item.menuName,
          children: children && children.length > 0 
            ? this.convertMenuTreeToCascader(children) 
            : undefined
        };
        // 如果没有子节点，删除 children 属性
        if (!node.children) {
          delete node.children;
        }
        return node;
      });
    },
    onDetail(id) {
      this.form.id = id;
      detail(id).then((res) => {
        if (res.code === 200 && res.data) {
          const menuId = res.data.menuId || null;

          this.form = {
            id: res.data.id || null,
            menuId: String(menuId),
            title: res.data.title || "",
            sort: res.data.sort || 0,
            wapImgUrl: res.data.wapImgUrl || "",
            pcImgUrl: res.data.pcImgUrl || "",
            contentIntroduce: res.data.contentIntroduce || "",
            fileUrl: res.data.fileUrl || "",
          };
          // 如果菜单树已加载，确保菜单ID能正确显示
          this.$nextTick(() => {
            // 确保菜单ID正确设置
            if (menuId && this.menuTreeOptions.length > 0) {
              // 查找节点路径，用于级联选择器显示
              const path = this.findNodePath(this.menuTreeOptions, String(menuId));
              if (path && path.length > 0) {
                // 如果找到路径，使用路径数组；否则使用ID
                this.form.menuId = path;
              } else {
                // 如果找不到路径，直接使用ID（可能是新添加的节点）
                this.form.menuId = String(menuId);
              }
            }
          });
        }
      });
    },
    // 处理菜单选择变化
    handleMenuChange(value) {
      // 当 emitPath: true 时，value 是路径数组，取最后一个值
      if (value !== null && value !== undefined) {
        if (Array.isArray(value) && value.length > 0) {
          // 如果是数组，取最后一个值（选中的节点ID）
          this.form.menuId = String(value[value.length - 1]);
        } else {
          this.form.menuId = String(value);
        }
      } else {
        this.form.menuId = null;
      }
    },
    // 查找节点在树中的路径
    findNodePath(tree, targetId, path = []) {
      for (const node of tree) {
        const currentPath = [...path, String(node.id)];
        if (String(node.id) === String(targetId)) {
          return currentPath;
        }
        if (node.children && node.children.length > 0) {
          const found = this.findNodePath(node.children, targetId, currentPath);
          if (found) {
            return found;
          }
        }
      }
      return null;
    },
    onSubmit() {
      const fn = this.form.id ? edit : create;
      
      // 确保 menuId 是字符串，不是数组
      let menuId = this.form.menuId;
      if (Array.isArray(menuId)) {
        // 如果是数组，取最后一个值
        menuId = menuId.length > 0 ? String(menuId[menuId.length - 1]) : null;
      } else if (menuId) {
        menuId = String(menuId);
      }
      
      const data = {
        ...this.form,
        menuId: menuId // 确保传递的是字符串
      };
      fn(data).then((res) => {
        if (res.code === 200) {
          this.$message.success(this.form.id ? "修改成功" : "创建成功");
          this.$emit("success");
        } else {
          this.$message.error(res.msg || "操作失败");
        }
      }).catch((error) => {
        this.$message.error("操作失败，请重试");
        console.error("操作失败:", error);
      });
    },
    onCancel() {
      this.$emit("cancel");
    },
  },
};
</script>
